//
//  SEGOrderInputViewController.m
//  Uhomebk
//
//  Created by 梁昆 on 2017/6/30.
//  Copyright © 2017年 com.segi. All rights reserved.
//
#import "SEGOrderInputHttpManager.h"
//#import "SEGBusinessManager.h"
#import "SEGOrderInputDetailViewController.h"
#import "SEGOrderInputCollectionViewCell.h"
#import "SEGOrderInputViewController.h"
#import "SEGOrderInputModel.h"
//#import "MyServiceListViewController.h"

#if __has_include(<Commom/SEGBigNavigationView.h>)
#import <Commom/SEGBigNavigationView.h>
#else
#import "SEGBigNavigationView.h"
#endif

static NSString *_SEGBaseCollectionViewCellIdentifier = @"SEGBaseCollectionViewCellIdentifier";

@interface SEGOrderInputViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,
                                            UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong)UICollectionView *baseCollcetionView; //主CollcetionView

@property (nonatomic, strong)SEGOrderInputHttpManager *orderInputManager; //工单录入网络请求Manager
/**
 我的服务红点
 */
@property (nonatomic, strong)UIImageView *myServiceRedImg;
/**
 大标题导航栏
 */
@property (nonatomic, strong)SEGBigNavigationView *bigNavView;

@end

@implementation SEGOrderInputViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - ======================< 生命周期 >========================
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    [self.view addSubview:self.baseCollcetionView];

    WeakSelf;
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    [self.bigNavView setTitleWithString:@"服务"];
    [self.bigNavView addRightButtonWithTitle:@"我的服务" tapBlock:^{
        [weakSelf onNavigationRightButtonClicked:nil];
    }];
    self.baseCollcetionView.frame =  CGRectMake(0, KBigNavHeight, LYScreenWidth(), LYScreenHeight()-KBigNavHeight-LYTabBarHeight());

    //新红点逻辑监听 4.4.0新增
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRedDot:) name:SEGAddReddotNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if ( self.isHomeEnter) {
        [self loadOrderInputListData];
    }
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}


#pragma mark - ======================< 我的服务 >========================
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    if ([self segCheckAuthor]) {
        // 清除红点
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:SEGConstOrderInputUserDefaults];
        UIViewController *myListCtl = [[SEGUhomeMediator sharedInstance] seg_initMyServiceListViewController:nil];
        myListCtl.title = @"我的服务";
        [self.navigationController pushViewController:myListCtl animated:YES];
        self.myServiceRedImg.hidden = YES;
        //删除物业服务红点
        [[SEGUhomeMediator sharedInstance] seg_deleteRedDotWithType:@{@"type" : kMessageTypeService}];
    }
}

-(BOOL)segCheckAuthor{
    
    SEGQueryauthinfoDataModel *data = [SEGQueryauthinfoManager sharedManager].QueryAuthInfo.data;
    if ([[SEGProfileManager sharedManager].profile.type isEqualToString:@"5"]) {
        SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
        [alertView showWithAlertTitle:nil text:SEGBasicBussinessStringDefine.promptUserAuthentication buttonTitlesArray:@[@"取消",@"申请认证"] actionBlock:^(NSInteger btnIndex) {
            if (btnIndex == 1) {
                [self.navigationController pushViewController:[[SEGUhomeMediator sharedInstance] seg_initSubmitUserAtuhViewController:nil] animated:YES];
            }
        }];
        
        return NO;
    }
    return YES;
}

#pragma mark - 红点相关
- (void)addRedDot:(NSNotification *)notification {
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            NSLog(@"ids = %@",ids);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 取出是否展示工单红点的状态
                BOOL isShowRed = [[NSUserDefaults standardUserDefaults] boolForKey:SEGConstOrderInputUserDefaults];
                //更新导航栏右侧按钮的红点
                [self.bigNavView updateRightButtonRedDot:isShowRed];
            });
        }
    }
}

#pragma mark - ======================< 数据加载 >========================
/**
 拉取工单录入界面数据源
 */
- (void)loadOrderInputListData{
    
    NSDictionary* params = @{@"communityId": kAccountCommunityID};

    [[SEGOrderInputHttpManager sharedManager] getOrderInputListDataWith:params type:_type finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed == NO) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            if (self.dataArray.count == 0) {
                [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.baseCollcetionView, @"text":kNoDataDefaultMessage}];
            } else {
                [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.baseCollcetionView, @"text":kNoDataDefaultMessage}];
            }
            return ;
        }
        //数据转模型
        NSMutableArray *arrM = [NSMutableArray array];
        id dataSource = result[@"data"];
        //1.工单录入，待客录单给的是数组格式
        if ([dataSource isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dict in result[@"data"]) {
                SEGOrderInputModel *model = [SEGOrderInputModel initWithDictionary:dict];
                [arrM addObject:model];
            }
        }
        else if ([dataSource isKindOfClass:[NSDictionary class]]){
            SEGOrderInputModel *model = [SEGOrderInputModel initWithDictionary:dataSource];
            [arrM addObject:model];
        }
        //存储数据源
        self.dataArray = arrM;
        [self.baseCollcetionView reloadData];
        
        if (self.dataArray.count == 0) {
            NSString *tipStr = kNoDataDefaultMessage;
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.baseCollcetionView, @"text":tipStr}];
        } else {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.baseCollcetionView, @"text":kNoDataDefaultMessage}];
        }
    }];
   
}

#pragma mark - ===============< UICollectionViewDataSource >=================
//组数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView
{
    return 1;
}

//Item的个数
- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

//每一个 Item
- (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
        SEGOrderInputCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:_SEGBaseCollectionViewCellIdentifier forIndexPath:indexPath];
        //普通工单、待客录单
        SEGOrderInputModel *inputModel = self.dataArray[indexPath.item];
        [cell paddDataWithInputModel:inputModel];
       
        return cell;
}

#pragma mark - ================<  UICollectionViewDelegate >==================

- (void)collectionView:(UICollectionView*)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath{
    
    if ([self segCheckAuthor]) {
        //跳转到工单录入详情 需要传界面来源信息
        SEGOrderInputModel *inputModel = self.dataArray[indexPath.item];
        SEGOrderInputDetailViewController* orderInputDetailVC = [[SEGOrderInputDetailViewController alloc] init];
        orderInputDetailVC.inputModel = inputModel;
        orderInputDetailVC.type = _type;
        orderInputDetailVC.userInfo = _userInfoDic;
        orderInputDetailVC.title = inputModel.aliasName;
        [self.navigationController pushViewController:orderInputDetailVC animated:YES];
    }
}

#pragma mark - ======================<  getter >========================
#pragma mark - getter
- (SEGBigNavigationView *)bigNavView {
    if (!_bigNavView) {
        _bigNavView = [[SEGBigNavigationView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), KBigNavHeight)];
        [self.view addSubview:_bigNavView];
    }
    return _bigNavView;
}
-(UICollectionView *)baseCollcetionView {
    if (!_baseCollcetionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        //宽度为屏幕宽度 - 2*1px （线的宽度）/ 3（一行分为3份）
        CGFloat itemWidth = (LYScreenWidth() - 2) / 3;
        CGFloat itemHeight = 100 * kScaleWidth;
        flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
        
        _baseCollcetionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        [_baseCollcetionView registerClass:[SEGOrderInputCollectionViewCell class] forCellWithReuseIdentifier:_SEGBaseCollectionViewCellIdentifier];
        UIColor *backColor = kColor_W;
        _baseCollcetionView.backgroundColor = backColor;
        _baseCollcetionView.delegate = self;
        _baseCollcetionView.dataSource = self;
    }
    return _baseCollcetionView;
}

-(SEGOrderInputHttpManager *)orderInputManager{
    if (!_orderInputManager) {
        _orderInputManager = [[SEGOrderInputHttpManager alloc] init];
    }
    return _orderInputManager;
}

-(NSMutableArray *)tempArray {
    if (!_tempArray) {
        _tempArray = [NSMutableArray array];
    }
    return _tempArray;
}

- (void)ininMyServiceButton {
    NSString* aTitle = @"我的服务";
    CGSize size = STRING_SIZE_FONT(1000, aTitle, 13);
    UIButton* historyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    historyBtn.frame = CGRectMake(0, 0, size.width, 20);
    [SEGUtils setObj:historyBtn WithSize:13 textColor:nil];
    [historyBtn setTitle:aTitle forState:UIControlStateNormal];
    [historyBtn addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [historyBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
    
    UIImage* aImage = [UIImage imageWithContentsOfFile:SEGPicName(@"tab_red_round")];
    self.myServiceRedImg = [[UIImageView alloc] initWithImage:aImage];
    self.myServiceRedImg.frame = CGRectMake(CGRectGetMaxX(historyBtn.frame) - aImage.size.width / 2.0, 0, aImage.size.width, aImage.size.height);
    [historyBtn addSubview:self.myServiceRedImg];
 
    // 取出是否展示工单红点的状态
    BOOL isShowRed = [[NSUserDefaults standardUserDefaults] boolForKey:SEGConstOrderInputUserDefaults];
    self.myServiceRedImg.hidden = !isShowRed;
 
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:historyBtn];
}

@end
